package com.eonmind.vip.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.eonmind.common.contract.enums.vip.AiCostEnum;
import com.eonmind.common.contract.enums.vip.ConsumptionTypeEnum;
import com.eonmind.common.contract.timer.Timer;
import com.eonmind.common.provider.entity.vip.PointsConsumption;
import com.eonmind.common.provider.entity.vip.UserWelfare;
import com.eonmind.common.provider.dto.VipDto;
import com.eonmind.vip.mapper.PointsMapper;
import com.eonmind.vip.mapper.UserWelfareMapper;
import com.eonmind.vip.provider.VipToUserServerProvider;
import com.eonmind.vip.service.VipToAiService;
import jakarta.validation.constraints.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class VipToAiServiceImpl implements VipToAiService {
    @Autowired
    private UserWelfareMapper userWelfareMapper;

    @Autowired
    private PointsMapper pointsMapper;

    @Autowired
    private VipToUserServerProvider vipToUserServerProvider;

    /**
     * @Override public VipDto.VipBackToAiIsAcResponse isAiChatAc(Long userId) {
     * UserWelfare userWelfare = userWelfareMapper.getUserPlanByUserID(userId);
     * VipDto.VipBackToAiIsAcResponse res = new VipDto.VipBackToAiIsAcResponse();
     * if (ObjectUtil.isEmpty(userWelfare)) {
     * return res.setCost(0).setIsAccess(false).setDesc("系统出错");
     * }
     * UserWelfare.CachedFeatures.Features features = userWelfare.getCachedFeatures().getFeatures();
     * if (features.getChat()) {
     * return res.setCost(0).setIsAccess(true).setDesc("会员权益通道，免积分");
     * }
     * Integer totalCoins = userWelfare.getCachedFeatures().getTotalCoins();
     * totalCoins -= AiCostEnum.AI_CHAT_COST.getCost();
     * Boolean isSuc = updateUserPlan(userId, totalCoins);
     * if (!isSuc) {
     * return res.setCost(0).setIsAccess(false).setDesc("积分不足");
     * }
     * return res.setIsAccess(true).setCost(AiCostEnum.AI_CHAT_COST.getCost()).setDesc("本次消费" + AiCostEnum.AI_CHAT_COST.getCost());
     * }
     * @Override public VipDto.VipBackToAiIsAcResponse isAiDrawAc(Long userId) {
     * UserWelfare userWelfare = userWelfareMapper.getUserPlanByUserID(userId);
     * VipDto.VipBackToAiIsAcResponse res = new VipDto.VipBackToAiIsAcResponse();
     * if (ObjectUtil.isEmpty(userWelfare)) {
     * return res.setCost(0).setIsAccess(false).setDesc("系统出错");
     * }
     * UserWelfare.CachedFeatures.Features features = userWelfare.getCachedFeatures().getFeatures();
     * if (features.getDrawing()) {
     * return res.setCost(0).setIsAccess(true).setDesc("会员权益通道，免积分");
     * }
     * Integer totalCoins = userWelfare.getCachedFeatures().getTotalCoins();
     * totalCoins -= AiCostEnum.AI_DRAW_COST.getCost();
     * Boolean isSuc = updateUserPlan(userId, totalCoins);
     * if (!isSuc) {
     * return res.setCost(0).setIsAccess(false).setDesc("积分不足");
     * }
     * return res.setIsAccess(true).setCost(AiCostEnum.AI_DRAW_COST.getCost()).setDesc("本次消费" + AiCostEnum.AI_DRAW_COST.getCost());
     * }
     * @Override public VipDto.VipBackToAiIsAcResponse isAiVideoAc(Long userId) {
     * UserWelfare userWelfare = userWelfareMapper.getUserPlanByUserID(userId);
     * VipDto.VipBackToAiIsAcResponse res = new VipDto.VipBackToAiIsAcResponse();
     * if (ObjectUtil.isEmpty(userWelfare)) {
     * return res.setCost(0).setIsAccess(false).setDesc("系统出错");
     * }
     * UserWelfare.CachedFeatures.Features features = userWelfare.getCachedFeatures().getFeatures();
     * if (features.getVideo()) {
     * return res.setCost(0).setIsAccess(true).setDesc("会员权益通道，免积分");
     * }
     * Integer totalCoins = userWelfare.getCachedFeatures().getTotalCoins();
     * totalCoins -= AiCostEnum.AI_VIDEO_COST.getCost();
     * Boolean isSuc = updateUserPlan(userId, totalCoins);
     * if (!isSuc) {
     * return res.setCost(0).setIsAccess(false).setDesc("积分不足");
     * }
     * return res.setIsAccess(true).setCost(AiCostEnum.AI_VIDEO_COST.getCost()).setDesc("本次消费" + AiCostEnum.AI_VIDEO_COST.getCost());
     * }
     **/

    @Override
    public VipDto.VipBackToAiIsAcResponse isAc(VipDto.VipAiServerDesc vipAiServerDesc) {
        Long userId = vipAiServerDesc.getUserId();
        if (ObjectUtil.isEmpty(userId)) {
            return null;
        }
        UserWelfare userWelfare = userWelfareMapper.getUserPlanByUserID(userId);
        if (ObjectUtil.isEmpty(userWelfare)) {
            vipToUserServerProvider.initUserWelfare(userId);
            userWelfare = userWelfareMapper.getUserPlanByUserID(userId);
        }

        VipDto.VipBackToAiIsAcResponse res = new VipDto.VipBackToAiIsAcResponse();
        Integer freeVideoTime = userWelfare.getCachedFeatures().getFeatures().getVideo();
        Integer freeDrawTime = userWelfare.getCachedFeatures().getFeatures().getDrawing();
        // 如果有免费绘画次数，则优先使用免费次数
        if (ConsumptionTypeEnum.AI_DRAW.getCode().equals(vipAiServerDesc.getType()) && freeDrawTime != null && freeDrawTime > 0) {
            freeDrawTime -= 1;
            updateUserWelfare(userId, freeDrawTime, freeVideoTime);
            res.setCost(0).setDesc("使用免费绘画次数，不消耗积分").setIsAccess(true);
            return res;
        }
        // 如果有免费视频次数，则优先使用免费次数
        if (ConsumptionTypeEnum.AI_VIDEO.getCode().equals(vipAiServerDesc.getType()) && freeDrawTime != null && freeVideoTime > 0) {
            freeVideoTime -= 1;
            updateUserWelfare(userId, freeDrawTime, freeVideoTime);
            res.setCost(0).setDesc("使用免费视频次数，不消耗积分").setIsAccess(true);
            return res;
        }
        if (ObjectUtil.isEmpty(userWelfare.getCachedFeatures()) || ObjectUtil.isEmpty(userWelfare.getCachedFeatures().getFeatures())) {
            return res.setCost(0).setIsAccess(false).setDesc("系统出错");
        }
        UserWelfare.CachedFeatures.Features features = userWelfare.getCachedFeatures().getFeatures();
        Integer totalCoins = userWelfare.getCachedFeatures().getTotalCoins();
        Integer usedCoins = userWelfare.getCachedFeatures().getUsedCoins();
        if (ObjectUtil.isEmpty(totalCoins)) {
            return res.setCost(0).setIsAccess(false).setDesc("系统出错");
        }
        totalCoins -= vipAiServerDesc.getCost();
        usedCoins += vipAiServerDesc.getCost();
        Boolean isSuc = updateUserPlan(userId, totalCoins, usedCoins);
        if (!isSuc) {
            return res.setCost(0).setIsAccess(false).setDesc("积分不足");
        }
        // 保存消费记录
        saveConsumption(vipAiServerDesc, totalCoins);
        return res.setIsAccess(true)
                .setCost(vipAiServerDesc.getCost())
                .setDesc("本次消费" + vipAiServerDesc.getCost());
    }

    @NotNull
    private Boolean updateUserPlan(Long userId, Integer totalCoins, Integer usedCoins) {
        if (totalCoins >= 0) {
            UserWelfare userWelfareBuilder = UserWelfare.builder()
                    .updateTime(Timer.currentTimestamp())
                    .cachedFeatures(
                            new UserWelfare.CachedFeatures()
                                    .setTotalCoins(totalCoins)
                                    .setUsedCoins(usedCoins)
                                    .setFeatures(new UserWelfare.CachedFeatures.Features())
                    ).build();
            userWelfareMapper.updateUserPlanByUserID(userId, userWelfareBuilder);
            return true;
        }
        return false;
    }

    @NotNull
    private Boolean updateUserWelfare(Long userId, Integer freeDrawTime, Integer freeVideoTime) {
        UserWelfare userWelfareBuilder = UserWelfare.builder()
                .updateTime(Timer.currentTimestamp())
                .cachedFeatures(
                        new UserWelfare.CachedFeatures()
                                .setFeatures(new UserWelfare.CachedFeatures.Features()
                                        .setVideo(freeVideoTime)
                                        .setDrawing(freeDrawTime)
                                )
                ).build();
        userWelfareMapper.updateUserPlanByUserID(userId, userWelfareBuilder);
        return true;
    }

    private void saveConsumption(VipDto.VipAiServerDesc vipAiServerDesc, Integer balance) {

        PointsConsumption pointsConsumption = new PointsConsumption()
                .setConsumption(-vipAiServerDesc.getCost())
                .setType(1)
                .setCategory(ConsumptionTypeEnum.getDescByCode(vipAiServerDesc.getType()))
                .setBalance(balance)
                .setDel(0)
                .setUpdateTime(Timer.currentTimestamp())
                .setCreateTime(Timer.currentTimestamp())
                .setUserID(vipAiServerDesc.getUserId())
                .setDescription(ConsumptionTypeEnum.getDescByCode(vipAiServerDesc.getType()) + "服务，使用模型为" + vipAiServerDesc.getModelName() + "，共消费 " + vipAiServerDesc.getCost() + "积分")
                .setModelName(vipAiServerDesc.getModelName());
        pointsMapper.save(pointsConsumption);
    }
}
